package com.winit.schedule.job.tracker.remoting;

import io.netty.channel.ChannelHandlerContext;

import com.winit.schedule.core.event.EventHandler;
import com.winit.schedule.core.protocol.Protocol;
import com.winit.schedule.core.protocol.command.QuartzRequest;
import com.winit.schedule.core.repository.entity.QuartzLogEntity;
import com.winit.schedule.job.tracker.event.QuartzEvent;
import com.winit.schedule.job.tracker.event.QuartzEventType;
import com.winit.schedule.remoting.exception.RemotingCommandException;
import com.winit.schedule.remoting.protocol.RemotingCommand;

@SuppressWarnings({ "unchecked", "rawtypes" })
public class QuartzProcessor extends AbstractProcessor {

    private final EventHandler eventHandler;

    public QuartzProcessor(RemotingService remotingService){
        super(remotingService);
        this.eventHandler = remotingService.getJobTrackerContext().getDispatcher().getEventHandler();
    }

    @Override
    public RemotingCommand processRequest(ChannelHandlerContext ctx, RemotingCommand request)
                                                                                             throws RemotingCommandException {
        QuartzRequest body = request.getBody();

        QuartzLogEntity logEntity = body.getLogEntity();
        if (null != logEntity) {
            eventHandler.handle(new QuartzEvent(QuartzEventType.QUARTZ_LOG, logEntity));
        }

        return RemotingCommand.createResponseCommand(Protocol.ResponseCode.SUCCESS.code(), "quartz request success!");
    }

}
